from PySide6.QtCore import Signal, QThread

from api import api_invoice


class InvoiceThread(QThread):
    finished_signal = Signal(int)
    rel_tip_signal = Signal(str, str)

    def __init__(self, file_path, secret_id, secret_key):
        super().__init__()
        self.secret_id = secret_id
        self.secret_key = secret_key

        self.file_path = file_path

    def run(self):
        invoice_identify = api_invoice.InvoiceIdentify(self.file_path, self.secret_id, self.secret_key)
        invoice_identify.rel_tip_signal.connect(self.rel_tip_signal)
        file_data = invoice_identify.f1()
        pdf_count = file_data['TotalPDFCount']
        if pdf_count != 1:
            self.rel_tip_signal.emit(f'暂时仅支持单发票文件，文件{self.file_path}包含{pdf_count}个发票文件，已跳过')
            self.finished_signal.emit(0)
            return
        invoice_data = file_data['MixedInvoiceItems'][0]
        invoice_type = invoice_data['SubType']
        invoice_type_name = invoice_data['SubTypeDescription']
        invoice_info = invoice_data['SingleInvoiceInfos'][invoice_type]
        title = invoice_info['Title']
        code = invoice_info.get('Code', '')
        number = invoice_info['Number']
        date = invoice_info['Date']
        pretax_amount = invoice_info['PretaxAmount']
        tax = invoice_info['Tax']
        total = invoice_info['Total']
        total_cn = invoice_info['TotalCn']
        seller = invoice_info['Seller']
        seller_tax_id = invoice_info['SellerTaxId']
        buyer = invoice_info['Buyer']
        buyer_tax_id = invoice_info['BuyerTaxId']
        issuer = invoice_info['Issuer']         # 开票人
        remark = invoice_info['Remark']
        vat_ele_item = next(value for value in invoice_info.values() if type(value) == list)[0]       # 查找值为列表的键值对，即为发票项目信息



        self.finished_signal.emit(1)


